const io = require('socket.io')(8900, {
    cors: {
        origin: "*",
    }
})

let users = [];

// 用户连接成功
const addUser = (userId, socketId) => {
    !users.some(user => user.userId === userId) &&
        users.push({ userId, socketId })
    console.log(users, "加入");
}

// 用户断开连接
const removeUser = (socketId) => {
    users = users.filter(user => user.socketId !== socketId)
    console.log(users, "离开");
}

// 获取当前用户
const getUser = (userId) => {
    console.log(userId, "获取");
    return users.find(user => user.userId === userId)
}

io.on("connection", (socket) => {
    // 普通用户
    console.log("用户连接成功.....");
    // take userId and socketId from user(从用户中获取用户Id和套接字Id)
    // 现在登录的用户
    socket.on('addUser', (userId) => {
        addUser(userId, socket.id)
        io.emit('getUsers', users)
    })

    //发送和获取发送的信息
    socket.on('sendMessage', ({ senderId, receiverId, text }) => {
        const user = getUser(receiverId)
        console.log(user, '用户');
        io.to(user?.socketId).emit('getMessage', {
            senderId,
            text,
        })
    })

    // 用户断开连接
    socket.on('disconnect', () => {
        console.log('用户断开连接......');
        console.log(socket.id);
        removeUser(socket.id)
        io.emit('getUsers', users)
    })

});